package com.example.controller;

import com.example.model.SqlExecution;
import com.example.model.SqlHistory;
import com.example.service.SqlTranslateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/api/translate")
public class SqlTranslateController {
    private static final Logger log = LoggerFactory.getLogger(SqlTranslateController.class);
    
    @Autowired
    private SqlTranslateService sqlTranslateService;

    @PostMapping
    public ResponseEntity<Map<String, String>> translate(
            @RequestBody Map<String, String> request,
            @RequestAttribute Long userId
    ) {
        log.info("接收到翻译请求，用户ID: {}, 文本: {}", userId, request.get("text"));
        String sql = sqlTranslateService.translateToSql(request.get("text"), userId);
        Map<String, String> response = new HashMap<>();
        response.put("sql", sql);
        log.info("翻译完成，用户ID: {}, 生成SQL: {}", userId, sql);
        return ResponseEntity.ok(response);
    }
    
    @PostMapping("/with-connection")
    public ResponseEntity<Map<String, String>> translateWithConnection(
            @RequestBody Map<String, Object> request,
            @RequestAttribute Long userId
    ) {
        String text = (String) request.get("text");
        Long connectionId = Long.valueOf(request.get("connectionId").toString());
        
        log.info("接收到带连接的翻译请求，用户ID: {}, 连接ID: {}, 文本: {}", userId, connectionId, text);
        String sql = sqlTranslateService.translateToSql(text, userId, connectionId);
        Map<String, String> response = new HashMap<>();
        response.put("sql", sql);
        log.info("带连接的翻译完成，用户ID: {}, 连接ID: {}, 生成SQL: {}", userId, connectionId, sql);
        return ResponseEntity.ok(response);
    }

    @GetMapping("/history")
    public ResponseEntity<?> getHistory(
            @RequestAttribute Long userId,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize
    ) {
        log.info("获取翻译历史，用户ID: {}, 页码: {}, 每页大小: {}", userId, page, pageSize);
        try {
            // 构建响应数据，包含分页信息和记录列表
            Map<String, Object> response = new HashMap<>();
            List<SqlHistory> records = sqlTranslateService.getUserHistoryPaged(userId, page, pageSize);
            int total = sqlTranslateService.getUserHistoryCount(userId);
            
            response.put("records", records);
            response.put("total", total);
            response.put("page", page);
            response.put("pageSize", pageSize);
            
            log.info("获取翻译历史成功，用户ID: {}, 总记录数: {}", userId, total);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取翻译历史失败，用户ID: {}", userId, e);
            Map<String, String> error = new HashMap<>();
            error.put("message", "获取历史记录失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    @GetMapping("/executions")
    public ResponseEntity<List<SqlExecution>> getExecutions(
            @RequestAttribute Long userId,
            @RequestParam(required = false, defaultValue = "50") Integer limit
    ) {
        log.info("获取SQL执行记录，用户ID: {}, 限制数量: {}", userId, limit);
        List<SqlExecution> executions = sqlTranslateService.getUserExecutions(userId, limit);
        log.info("获取SQL执行记录成功，用户ID: {}, 记录数量: {}", userId, executions.size());
        return ResponseEntity.ok(executions);
    }

    @PostMapping("/execute")
    public ResponseEntity<?> executeSql(
            @RequestBody Map<String, String> request, 
            @RequestAttribute Long userId
    ) {
        String sql = request.get("sql");
        log.info("接收到SQL执行请求，用户ID: {}, SQL: {}", userId, sql);
        
        try {
            if (sql == null || sql.trim().isEmpty()) {
                log.warn("SQL执行失败，SQL语句为空，用户ID: {}", userId);
                return ResponseEntity.badRequest().body("SQL语句不能为空");
            }
            Map<String, Object> result = sqlTranslateService.executeSql(sql, userId);
            log.info("SQL执行成功，用户ID: {}, 结果行数: {}", userId, 
                    result.containsKey("rows") ? ((List<?>)result.get("rows")).size() : 0);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("SQL执行失败，用户ID: {}, SQL: {}", userId, sql, e);
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    
    @PostMapping("/execute-with-connection")
    public ResponseEntity<?> executeSqlWithConnection(
            @RequestBody Map<String, Object> request, 
            @RequestAttribute Long userId
    ) {
        String sql = (String) request.get("sql");
        Long connectionId = Long.valueOf(request.get("connectionId").toString());
        
        log.info("接收到带连接的SQL执行请求，用户ID: {}, 连接ID: {}, SQL: {}", userId, connectionId, sql);
        
        try {
            if (sql == null || sql.trim().isEmpty()) {
                log.warn("带连接的SQL执行失败，SQL语句为空，用户ID: {}, 连接ID: {}", userId, connectionId);
                return ResponseEntity.badRequest().body("SQL语句不能为空");
            }
            
            Map<String, Object> result = sqlTranslateService.executeSql(sql, connectionId, userId);
            log.info("带连接的SQL执行成功，用户ID: {}, 连接ID: {}, 结果行数: {}", 
                    userId, connectionId, result.containsKey("rows") ? ((List<?>)result.get("rows")).size() : 0);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("带连接的SQL执行失败，用户ID: {}, 连接ID: {}, SQL: {}", userId, connectionId, sql, e);
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
} 